package com.quad.innovators.salesease.lock.impl.local;

import cn.hutool.cache.impl.TimedCache;
import com.quad.innovators.salesease.lock.RepeatSubmitLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@Component
@Slf4j
public class DefaultRepeatSubmitLock implements RepeatSubmitLock {

    // 使用ConcurrentHashMap来存储每个key的锁
    //定义缓存，设置最大缓存数及过期日期
    private static final TimedCache<String,Object> CACHE = new TimedCache<>(5 * 1000);

    // 定时任务的调度器，负责定时释放锁
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    @Override
    public boolean tryLock(String key,long leaseTime) {
        boolean isLocked = false;
        try {
            // 尝试获取锁，最多等待waitTime时间
            isLocked = !CACHE.containsKey(key);
            if(isLocked) {
                CACHE.put(key,System.currentTimeMillis(), leaseTime * 1000);
                return true;
            }
        } catch (Exception e) {
            Thread.currentThread().interrupt();
        }
        return isLocked;
    }

    @Override
    public void unlock(String key) {
        if (CACHE.containsKey(key)) {
            CACHE.remove(key);
        }
    }

    public boolean isLocked(String key) {
        return CACHE.containsKey(key);
    }
}
